package com.umeox.watch.moto.launcher.fragment;


import static android.bluetooth.BluetoothAdapter.STATE_OFF;
import static android.bluetooth.BluetoothAdapter.STATE_ON;
import static android.net.wifi.WifiManager.WIFI_STATE_DISABLED;
import static android.net.wifi.WifiManager.WIFI_STATE_ENABLED;
import static com.umeox.moto.common.utils.NetUtils.isWifiEnabled;
import static com.umeox.moto.common.utils.NetworkUtil.NetworkType.MOBILE_2G;
import static com.umeox.moto.common.utils.NetworkUtil.NetworkType.MOBILE_3G;
import static com.umeox.moto.common.utils.NetworkUtil.NetworkType.MOBILE_4G;
import static com.umeox.moto.common.utils.NetworkUtil.NetworkType.MOBILE_UNKNOWN;
import static com.umeox.moto.common.utils.NetworkUtil.NetworkType.WIFI;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.umeox.moto.common.log.Logger;
import com.umeox.moto.common.utils.NetworkUtil;
import com.umeox.moto.watch.themes.app.ThemeFragment;
import com.umeox.moto.watch.themes.skin.loader.ResourceManager;
import com.umeox.watch.moto.launcher.R;
import com.umeox.watch.moto.launcher.adapter.QuickSettingsAdapter;
import com.umeox.watch.moto.launcher.bean.QuickSettingsBean;
import com.umeox.watch.moto.launcher.constant.AppEntry;
import com.umeox.watch.moto.launcher.event.DeviceStateChangedListener;
import com.umeox.moto.watch.themes.ItemClickListener;
import com.umeox.watch.moto.launcher.event.OnItemLongClickListener;
import com.umeox.watch.moto.launcher.itemdecoration.QuickSettingDecoration;
import com.umeox.watch.moto.launcher.ui.ThemeActivity;
import com.umeox.watch.moto.launcher.ui.VolumeActivity;
import com.umeox.watch.moto.launcher.base.DeviceStatusManager;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Rambo 2019-07-04
 * Describe:
 */
public class QuickSettingsFragment extends ThemeFragment implements ItemClickListener, OnItemLongClickListener, DeviceStateChangedListener {

    private static final int[] mResIdArr = {
            R.drawable.icon_wifi_off,
            R.drawable.icon_volume,
            R.drawable.brightness_level,
            R.drawable.ic_bluetooth_off,
            R.drawable.icon_theme,
            R.drawable.icon_setting
    };
    public static final String ACTION_SIM_STATE_CHANGED = "android.intent.action.SIM_STATE_CHANGED";
    public static final int BRIGHTNESS_DEFAULT = 64;

    private static QuickSettingsFragment INSTANCE;
    private RecyclerView mQuickSettingRv;
    private QuickSettingsAdapter mAdapter;
    private ImageView mNetworkTypeIv;
    private ImageView mSignalIv;
    private GridLayoutManager mLayoutManager;
    private WifiManager mWifiManager;
    private int mBrightnessPercent;

    private BluetoothAdapter mBluetoothAdapter;
    private IntentFilter mWifiStateIntentFilter;
    private boolean isReceiverRegistered;
    private boolean isBluetoothReceiverRegistered;
    public static final String PKG_SETTINGS = "com.umeox.s21wifi";
    public static final String CLASS_SETTINGS_BLUETOOTH = "com.umeox.s21wifi.bluetooth.BluetoothSettingActivity";

    public QuickSettingsFragment() {
        INSTANCE = this;
    }

    public static QuickSettingsFragment getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new QuickSettingsFragment();
        }
        return INSTANCE;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.frag_quick_settings;
    }

    @Override
    protected void initView(View rootView) {
        super.initView(rootView);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mWifiManager = (WifiManager) mContext.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        mQuickSettingRv = rootView.findViewById(R.id.rv_quick_setttings);
        mQuickSettingRv.setHasFixedSize(true);
        mLayoutManager = new GridLayoutManager(getContext(), 3);
        mQuickSettingRv.setLayoutManager(mLayoutManager);
        mNetworkTypeIv = rootView.findViewById(R.id.iv_network_type);
        mSignalIv = rootView.findViewById(R.id.iv_signal_level);
        mAdapter = new QuickSettingsAdapter();
        mAdapter.setItemClickListener(this);
        mAdapter.setOnItemLongClickListener(this);
        mQuickSettingRv.setAdapter(mAdapter);
        QuickSettingDecoration decoration = new QuickSettingDecoration(0, 12);
        mQuickSettingRv.addItemDecoration(decoration);
        List<QuickSettingsBean> dataList = new ArrayList<>(mResIdArr.length);

        for (int resId : mResIdArr) {
            QuickSettingsBean qsb = new QuickSettingsBean();
            qsb.setIconResId(resId);
            dataList.add(qsb);
        }
        mAdapter.setDataList(dataList);
        setupBrightness();
        mQuickSettingRv.post(this::setBrightnessImageLevel);
        refreshBluetoothStatus();
    }

    public void refreshBluetoothStatus() {
        mResIdArr[0] = isWifiEnabled() ? R.drawable.icon_wifi_on : R.drawable.icon_wifi_off;
        mResIdArr[3] = mBluetoothAdapter.isEnabled() ? R.drawable.ic_bluetooth_on : R.drawable.ic_bluetooth_off;
        IntentFilter mBluetoothStateIntentFilter = new IntentFilter();
        mBluetoothStateIntentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        mContext.registerReceiver(mBluetoothStateReceiver, mBluetoothStateIntentFilter);
        isBluetoothReceiverRegistered = true;
    }

    private static final String TAG = "QuickSettingsFragment";
    private final BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "onReceive: " + intent.getAction());
            final String action = intent.getAction();
            if (action == null) {
                return;
            }
            if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
                int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
                switchWifiState(wifiState);
            }

        }
    };

    private final BroadcastReceiver mBluetoothStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "onReceive: " + intent.getAction());
            final String action = intent.getAction();
            if (action == null) {
                return;
            }
            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                final int bluetooth = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                switchBluetooth(bluetooth);
            }

        }
    };


    private void switchWifiState(int wifiState) {
        switch (wifiState) {
            case WIFI_STATE_DISABLED:
                notifyItemStateChange(0, R.drawable.icon_wifi_off);
                break;
            case WIFI_STATE_ENABLED:
                notifyItemStateChange(0, R.drawable.icon_wifi_on);
                break;
            default:
        }
    }

    private void switchBluetooth(int bluetooth) {
        switch (bluetooth) {
            case STATE_OFF:
                notifyItemStateChange(3, R.drawable.ic_bluetooth_off);
                break;
            case STATE_ON:
                notifyItemStateChange(3, R.drawable.ic_bluetooth_on);
                break;
            default:
        }
    }

    private void notifyItemStateChange(int index, int resId) {

        if (mLayoutManager == null) {
            return;
        }

        final View childView = mLayoutManager.getChildAt(index);
        if (childView != null) {
            ((ImageView) childView).setImageResource(resId);
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        registerNetWorkReceiver(true);
    }


    @Override
    public void onPause() {
        super.onPause();
        registerNetWorkReceiver(false);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        registerNetWorkReceiver(false);
        if (isBluetoothReceiverRegistered) {
            mContext.unregisterReceiver(mBluetoothStateReceiver);
            isBluetoothReceiverRegistered = false;
        }
    }

    private void setBrightnessImageLevel() {
        final View view = mLayoutManager.getChildAt(2);
        if (view != null) {
            ImageView imageView = view.findViewById(R.id.iv_quick_setting);
            imageView.setImageLevel(mBrightnessPercent);
        }
    }

    private void setupBrightness() {
        try {
            int value = Settings.System.getInt(mContext.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
            mBrightnessPercent = Math.max(value / BRIGHTNESS_DEFAULT, 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 注册和反注册网络信号状态
     *
     * @param register
     */
    private void registerNetWorkReceiver(boolean register) {
        if (mContext == null) {
            return;
        }
        final DeviceStatusManager deviceStatusManager = DeviceStatusManager.getInstance();

        if (register) {
            deviceStatusManager.addDeviceStateChangedListener(this);
            mWifiStateIntentFilter = new IntentFilter();
            mWifiStateIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
            mContext.registerReceiver(mWifiStateReceiver, mWifiStateIntentFilter);
            isReceiverRegistered = true;
        } else {
            if (mWifiStateIntentFilter != null && isReceiverRegistered) {
                mContext.unregisterReceiver(mWifiStateReceiver);
                isReceiverRegistered = false;
            }
            deviceStatusManager.removeDeviceStateChangedListener(this);
        }
    }

    @Override
    public void onItemLongClicked(int position) {
        if (position == 0 && isWifiEnabled()) {
            launchApp(AppEntry.WifiSettings.PKG, AppEntry.WifiSettings.CLS);
        } else if (position == 3 && mBluetoothAdapter.isEnabled()) {
            Intent intent = new Intent();
            intent.setClassName(PKG_SETTINGS, CLASS_SETTINGS_BLUETOOTH);
            startActivity(intent);
        }
    }


    /**
     * 0wifi 1音量 2闹钟 3画板 4通知 5设置
     *
     * @param position
     */
    @Override
    public void onItemClicked(int position) {
        switch (position) {
            case 0:
                mWifiManager.setWifiEnabled(!isWifiEnabled());
                break;
            case 1:
                VolumeActivity.start(getContext());
                break;
            case 2:
                if (mBrightnessPercent >= 6) {
                    mBrightnessPercent = 1;
                } else {
                    mBrightnessPercent++;
                }
                setBrightnessImageLevel();
                final int value = mBrightnessPercent * BRIGHTNESS_DEFAULT;
                Settings.System.putInt(mContext.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, Math.min(value, 255));
                break;
            case 3:
                setBluetoothEnable(!mBluetoothAdapter.isEnabled());
                break;
            case 4:
                startActivity(new Intent(getActivity(), ThemeActivity.class));
                break;
            case 5:
                launchApp(AppEntry.Settings.PKG, AppEntry.Settings.CLS);
                break;
        }

    }

    private void launchApp(String pkg, String cls) {
        Intent intent = new Intent();
        intent.setClassName(pkg, cls);
        startActivity(intent);
    }


    private void initActiveNetworkType(String networkType) {
        mNetworkTypeIv.setVisibility(View.VISIBLE);
        Logger.d(TAG, "initActiveNetworkType: " + networkType);
        if (WIFI.equals(networkType)) {
            mNetworkTypeIv.setImageDrawable(ResourceManager.getInstance().getDrawable(R.drawable.signal_wifi_level));
            return;
        }
        mNetworkTypeIv.setImageDrawable(ResourceManager.getInstance().getDrawable(R.drawable.cellular_level));
        switch (networkType) {
            case MOBILE_2G:
                mNetworkTypeIv.setImageLevel(2);
                break;
            case MOBILE_3G:
                mNetworkTypeIv.setImageLevel(3);
                break;
            case MOBILE_4G:
                mNetworkTypeIv.setImageLevel(4);
                break;
            case MOBILE_UNKNOWN:
            default:
                mNetworkTypeIv.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public void onSignalStatusChange(int state) {
        if (state == -1) {
            mSignalIv.setVisibility(View.GONE);
            if (!NetworkUtil.isNetworkTypeWifi(mContext)) {
                mNetworkTypeIv.setVisibility(View.GONE);
            }
            return;
        }
        mSignalIv.setVisibility(View.VISIBLE);
        mSignalIv.setImageLevel(state);
    }

    @Override
    public void onBatteryStatusChange(int batteryStatus, int batteryLevel) {

    }

    @Override
    public void onNetworkTypeChange(String networkType) {
        Log.d(TAG, "onWifiSignalLevelChange: " + networkType);
        initActiveNetworkType(networkType);
    }

    @Override
    public void onWifiSignalLevelChange(int wifiSignalLevel) {
        Log.d(TAG, "onWifiSignalLevelChange: " + wifiSignalLevel);
        mNetworkTypeIv.setImageLevel(wifiSignalLevel);
    }

    private void setBluetoothEnable(boolean checked) {
        if (checked) {
            mBluetoothAdapter.enable();
        } else {
            mBluetoothAdapter.disable();

        }
    }
}
